package com.bicon.botu.mall.order.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.mall.order.common.OrderConstans;
import com.bicon.botu.mall.order.entity.Invoice;
import com.bicon.botu.mall.order.mapper.InvoiceMapper;
import com.bicon.botu.mall.order.service.IInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *  个人发票业务层实现类
 * @author 李双喜
 * @since 2018-06-07
 */
@Service
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements IInvoiceService {

    @Autowired
    private InvoiceMapper invoiceMapper;
    
    @Override
    public Invoice saveOrUpdate(Invoice entity) {
        //根据UserId（用户ID）、type(发票类型) 查询是否已存在记录
        int count=invoiceMapper.selectCount(new EntityWrapper<Invoice>().eq("user_id", entity.getUserId())
                .eq("type",entity.getType()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //重置当前用户下所有发票记录标识
        Invoice Invoice=new Invoice();
        Invoice.setState(OrderConstans.MYINVOICE_STATE_0);
        invoiceMapper.update(Invoice,new EntityWrapper<Invoice>().eq("user_id", entity.getUserId())
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //根据数据库记录，执行新增或修改
        if(count==0){
            entity.preInsert();
            entity.setState(OrderConstans.MYINVOICE_STATE_1);
            invoiceMapper.insert(entity);
        }else{
            entity.preUpdate();
            entity.setState(OrderConstans.MYINVOICE_STATE_1);
            invoiceMapper.update(entity,new EntityWrapper<Invoice>().eq("user_id", entity.getUserId())
                    .eq("type",entity.getType()));
        }
        //返回默认发票信息
        Invoice.setState(OrderConstans.MYINVOICE_STATE_1);
        Invoice.setUserId(entity.getUserId());
        return invoiceMapper.selectOne(Invoice);
    }
}
